<?php

namespace app\http\middleware;

use app\admin\model\AdminModel;
use app\admin\model\PermissionModel;
use app\admin\model\SystemModel;
use think\facade\Session;
use think\facade\View;

class AdminAuth
{
    /**
     * 后台路由认证中间件
     * @param $request
     * @param \Closure $next
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function handle($request, \Closure $next)
    {
        // 获取系统信息
        View::share('systemConfig', SystemModel::getConfigInfo(['Site']));
        // 获取Uri
        $uri = getUri($request->url());
        // 验证特殊路由
        if ($uri == '/admin/login' ||
            $uri == "/admin/logout" ||
            $uri == '/admin') {
            return $next($request);
        }
        // 获取登录态
        $adminId = Session::get('admin');
        if (!$adminId) {
            return redirect('/admin/login');
        }
        // 查询登录用户
        $admin = AdminModel::find($adminId);
        $request->AdminAuth = $admin;
        View::share('admin', $admin);
        // 获取登录拥有权限
        $permissionsLists = PermissionModel::where('role_id', $admin->role_id)
            ->field('concat("/admin/",controller,"/",method) as menus,level1')
            ->select()
            ->toArray();
        $permissions['menus_item'] = array_unique(array_column($permissionsLists, 'menus'));
        $permissions['menus_level1_name'] = array_unique(array_column($permissionsLists, 'level1'));
        $permissions['menus_item'][] = '/admin/index';
        $permissions['menus_item'][] = '/admin/desktop';
        // 获取面包屑内容
        $crumbs = PermissionModel::where('role_id', $admin->role_id)
            ->whereRaw('concat(controller,"/",method) = :uri', ['uri' => getControllerAndMethod($uri)])
            ->field('level1,level2,level3')->find();
        View::share('crumbs', $crumbs);
        // 验证有无权限
        if (in_array($uri, $permissions['menus_item'])) {
            $request->AdminPersimmon = $permissions;
            return $next($request);
        } else {
            return baseResponse(999, '暂无权限');
        }
    }
}
